package middleware.optimize;

import middleware.llvm.BasicBlock;
import middleware.llvm.instruction.AllocaInstruction;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 构建冲突图的类
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public class ConflictDiagramBuilder {
    private final ConflictDiagram conflictDiagram;

    public ConflictDiagramBuilder(List<AllocaInstruction> allocaInstList, Map<BasicBlock, Set<AllocaInstruction>> activeSets, Map<BasicBlock, Set<AllocaInstruction>> inSets) {
        var blocks = activeSets.keySet();

        conflictDiagram = new ConflictDiagram(allocaInstList);

//        for (var block : blocks) {
//            var defSet = activeSets.get(block);
//            var inSet = inSets.get(block);
//            for (var def : defSet) {
//                if (!allocaInstList.contains(def)) {
//                    continue;
//                }
//                for (var in : inSet) {
//                    if (!allocaInstList.contains(in)) {
//                        continue;
//                    }
//                    if (def != in) {
//                        conflictDiagram.addConflict(def, in);
//                    }
//                }
//            }
//        }
        blocks.forEach(block -> {
            var defSet = activeSets.get(block);
            var inSet = inSets.get(block);
            defSet.stream()
                    .filter(allocaInstList::contains)
                    .forEach(def -> inSet.stream()
                            .filter(allocaInstList::contains)
                            .filter(in -> def != in)
                            .forEach(in -> conflictDiagram.addConflict(def, in)));
        });
    }


    public ConflictDiagram getConflictDiagram() {
        return conflictDiagram;
    }
}
